package cn.itcast.demo.locks;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.Collections;
import java.util.UUID;

/**
 * @author 虎哥
 */
public class ReentrantRedisLock implements RedisLock {

    private StringRedisTemplate redisTemplate;

    private String key;

    private String VALUE_PREFIX = UUID.randomUUID().toString();

    public ReentrantRedisLock(StringRedisTemplate redisTemplate, String key) {
        this.redisTemplate = redisTemplate;
        this.key = key;
    }

    private static final DefaultRedisScript<Long> LOCK_SCRIPT;
    private static final DefaultRedisScript<Object> UNLOCK_SCRIPT;

    private String releaseTime;

    static {
        LOCK_SCRIPT = new DefaultRedisScript<>();
        LOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("lock.lua")));
        LOCK_SCRIPT.setResultType(Long.class);

        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("unlock.lua")));
    }

    @Override
    public boolean tryLock(long releaseTime) {
        while (true) {
            String threadId = VALUE_PREFIX + Thread.currentThread().getId();
            this.releaseTime = String.valueOf(releaseTime);

            Long result = redisTemplate.execute(LOCK_SCRIPT, Collections.singletonList(key), threadId, this.releaseTime);
            if(result != null && result == 1){
                return true;
            }
        }
    }

    @Override
    public void unlock() {
        String threadId = VALUE_PREFIX + Thread.currentThread().getId();
        redisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(key), threadId, this.releaseTime);
    }
}
